package com.ncbee.base.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.ncbee.base.config.shiro.annotation.RequiresExtPermissions;
import com.ncbee.base.model.entity.BaseData;
import com.ncbee.base.model.vo.TreeVo;
import com.ncbee.base.service.BaseDataService;
import com.ncbee.base.util.StringUtils;
import com.ncbee.base.web.base.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author youdianyun
 * @since 2018-12-05
 */
@Controller
@RequestMapping("/baseData")
@RequiresExtPermissions("baseData:")
public class BaseDataController extends BaseController<BaseData> {
    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
    @Autowired
    private BaseDataService baseDataService;
    @Override
    protected IService<BaseData> getTargetService() {
        return baseDataService;
    }

    @Override
    public String getListPageUrl() {
        return "baseData/listPage";
    }

    @Override
    protected String getAddPageUrl() {

        return "baseData/addPage";
    }

    @Override
    protected String getEditPageUrl() {
        return "baseData/editPage";
    }

    /**
     * 显示添加页面之前
     */
    @Override
    protected void beforeShowAdd(HttpServletRequest request) {
        String pid=request.getParameter("pid");
        request.setAttribute("pid",pid);
    }

    /**
     * 查询所有的树节点
     * @return
     */
    @ResponseBody
    @RequestMapping("showBaseDataTree")
    public Object showBaseDataTree(){
        List<TreeVo> treeList=baseDataService.findBaseDataTree();
        return treeList;
    }
    /*
     * 删除当前资源之前，先删除当前资源的子节点
     */
    @Override
    protected void beforeDelete(HttpServletRequest request, String ids) {
        BaseData baseData=baseDataService.getById(ids);
        List<Long> idsList=new ArrayList<Long>();
        QueryWrapper<BaseData> queryWrapper=new QueryWrapper<BaseData>();
        queryWrapper.likeRight("pre_pid",baseData.getPrePid()+",");
        //查询当前资源的子资源
        List<BaseData> baseDataList=baseDataService.list(queryWrapper);
        for(BaseData r:baseDataList){
            idsList.add(r.getId());
        }
        if(idsList.size()>0){
            baseDataService.removeByIds(idsList);
        }

    }

    /**
     * 新增资源之后,维护子父级之间的关系
     */
    @Override
    protected void afterSave(HttpServletRequest request,BaseData baseData){
        Long id=baseData.getId();//获取返回的主键
        Long pid=baseData.getPid();//获取父id
        StringBuffer pidS=new StringBuffer();
        //如果没有选择父节点
        if(pid==null){
            pidS.append(id);
        }else{
            //选择了父节点
            BaseData parentBaseData=baseDataService.getById(pid);
            String parentPidS=parentBaseData.getPrePid();//获取父节点的所有上级资源
            pidS.append(parentPidS).append(",").append(id);
        }
        baseData.setPrePid(pidS.toString());
        baseData.setCreateTime(LocalDateTime.now());
        boolean flag=baseDataService.updateById(baseData);
        logger.info("---------新增资源成功维护子父级关系结果------："+flag);
    }
    /**
     *  显示更新页面之前
     *  查询当前资源以及当前资源子资源
     */
    @Override
    protected void beforeShowEdit(HttpServletRequest request, BaseData baseData){
        String prePid=baseData.getPrePid();
        QueryWrapper<BaseData> queryWrapper=new QueryWrapper<BaseData>();
        queryWrapper.likeRight("pre_pid",prePid+",");
        //查询子资源
        List<BaseData> baseDataList=baseDataService.list(queryWrapper);
        if(CollectionUtils.isEmpty(baseDataList)){
            baseDataList=new ArrayList<>();
        }
        baseDataList.add(baseData);
        String  baseDataListStr= JSONObject.toJSONString(baseDataList);
        request.setAttribute("baseDataListStr",baseDataListStr);
    }
    /**
     * 更新记录之前
     */
    @Override
    protected void beforeUpdate(HttpServletRequest request, BaseData baseData){
        // 判断节点的父id 是否改变了
        Long pid=baseData.getPid();
        BaseData dbBaseData=baseDataService.getById(baseData.getId());
        Long dbPid=dbBaseData.getPid();
        //无值相等 未改变
        if(pid==dbPid){
            return;
        }
        //有值相等,未改变
        if(pid!=null&&dbPid!=null){
            if(pid.intValue()==dbPid.intValue()){
                return;
            }
        }
        List<BaseData> updateList=new ArrayList<BaseData>();
        QueryWrapper<BaseData> queryWrapper=new QueryWrapper<BaseData>();
        //查询当前资源所有的子资源。
        queryWrapper.likeRight("pre_pid",baseData.getPrePid()+",");
        List<BaseData> childBaseDataList=baseDataService.list(queryWrapper);
        if(pid==null){//当前资源至于顶级节点
            baseData.setPrePid(baseData.getId()+"");
            for(BaseData r:childBaseDataList){
                String prePid=r.getPrePid();
                String newPrePid= StringUtils.getUpdatePidStr(prePid,baseData.getId()+"");
                r.setPrePid(newPrePid);
                updateList.add(r);
            }
        }else{
            BaseData parentBaseData=baseDataService.getById(pid);
            String parentPrePid=parentBaseData.getPrePid();//5,6
            String oldPrePid=baseData.getPrePid();//7
            String newPrePid= StringUtils.getUpdatePidStr(oldPrePid,baseData.getId()+"");
            baseData.setPrePid(parentPrePid+","+newPrePid);
            for(BaseData r:childBaseDataList){
                String prePid=r.getPrePid();
                String childNewPrePid= StringUtils.getUpdatePidStr(prePid,baseData.getId()+"");
                r.setPrePid(parentPrePid+","+childNewPrePid);
                updateList.add(r);
            }
        }
        if(!CollectionUtils.isEmpty(updateList)){
            boolean flag=baseDataService.updateBatchById(updateList);
            if(flag){
                logger.info("----成功维护了"+(updateList.size()+1)+"对父子关系---");
            }

        }
        //设置更新时间
        baseData.setUpdateTime(LocalDateTime.now());
    }
}

